//
//  XYReaderController.swift
//  XYReadBook
//
//  Created by fox on 2017/9/9.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

/// 从swift4.0到swift3.0
/// 阅读主控制器
class XYReaderController: XYViewController {

    /*如果属性你写了!号,那么你一定要在viewdidLoad方法给他赋值,不然会崩溃😖
     */
    var buttomView:XYBottomMenuView!
    var topMenuView:XYTopMenuView!
    var bookID:String
    var bookName:String
    var bookModel:XYReadModel
    var isHiddenTopBottonView:Bool = false
    var catalogueVC:XYCatalogueController! // 目录与书签
    var pageVC:UIPageViewController!
    var settingView = DZMRMSettingView()
    let fontDownload = XYFontDownload()
    /// 跳转最后一个章节
    var gotoChapter:(()->Void)?

    var rigthImtesVc:XYRigthItemController!
    var bookIcon:UIImageView
fileprivate var isShowRithItmes:Bool = false
    var pageIndex:Int {
        get {
            let pageIndexKey = self.bookModel.bookID + "pageIndex"
            let pageIndex = UserDefaults.standard.object(forKey: pageIndexKey)as? Int
            var indexPage = pageIndex ?? 0

            // TODO
            // 3行 4行  5行
            // 那么一个章节如果分3行排列 假设说有10页 ,那么切换到5行,此时index没有对应更改,那,那么就是数组越界.
            // 还有一个Bug暂时不想解决,就是每次更换行的时候,应该要记录当页码的文字,来决定这个index ,暂且放到后面再来处理
            if indexPage > bookModel.currentChapter.pageHeights.count - 1 {
                indexPage = bookModel.currentChapter.pageHeights.count - 1
            }
            return indexPage
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        let changeSoure = Notification.Name(rawValue: changeSoureNotificationKey)

        NotificationCenter.default.addObserver(self, selector:#selector(changeSoure(notification:)),
                                               name:changeSoure, object: nil)
    }


    func changeSoure(notification:NSNotification) {
        weak var weakSelf = self
        bookModel.getchapterList { (chapterList, error) in
            if let list = chapterList {
                self.catalogueVC.chapters = list
                weakSelf?.bookModel.loadData(callBack: {
                    weakSelf?.refreshReadView()
                })
            }
        }
        XYLog(messsage: notification.userInfo)
        /// 改变源数据
    }

    init(bookID:String,bookName:String,bookModel:XYReadModel,bookIcon:UIImageView) {
        self.bookID = bookID
        self.bookName = bookName
        self.bookModel = bookModel
        self.bookIcon = bookIcon
        super.init(nibName: nil, bundle: nil)
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.isNavigationBarHidden = true
        UIApplication.shared.isStatusBarHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        UIApplication.shared.isStatusBarHidden = false
    }
    override var prefersStatusBarHidden: Bool{
        return true
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        settingView.frame = CGRect.init(x: 0, y: ScreenHeight - 252, width: ScreenWidth, height: 252)
        buttomView.frame = CGRect.init(x: 0, y: ScreenHeight - 165, width: ScreenHeight, height: 290)
        topMenuView.frame =  CGRect.init(x: 0, y: 0, width: ScreenWidth, height: 64)
        rigthImtesVc.view.frame = CGRect.init(x: view.width * 0.5, y: topMenuView.frame.maxY + 6, width: view.width * 0.45, height: 280)
         rigthImtesVc.view.layer.cornerRadius = 6
    }


    func setupUI() {
        buttomView = XYBottomMenuView.init(frame: CGRect.zero)
        topMenuView = XYTopMenuView.init(frame: CGRect.zero,bookName:bookName)
        buttomView.slider.delegate = self
        topMenuView.delegate = self
        buttomView.delegate = self
        view.addSubview(buttomView)
        view.addSubview(topMenuView)


        
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(clickAutoHiddenMenuView))
        tap.delegate = self
        view.addGestureRecognizer(tap)
        catalogueVC = XYCatalogueController.init(bookID: bookID)
        addChildViewController(catalogueVC)
        view.addSubview(catalogueVC.view)
        catalogueVC.view.frame = CGRect.init(x: -ScreenWidth, y: 0, width: ScreenWidth, height:ScreenHeight)
        catalogueVC.view.isHidden = true
        weak var weakSelf = self
        catalogueVC.bookIndexVC.didSelectRowAt = {(row:Int) in
            weakSelf?.bookModel.updateIndex(row, with: {
                weakSelf?.gotoChapterController()
                weakSelf?.updateSliderValue()
            })
        }

        view.addSubview(settingView)
        settingView.isHidden = true
        settingView.colorView.selectBtn = {(btn,colors) in

            DZMReadConfigure.shared().colorIndex = btn.tag
            weakSelf?.refreshReadView()
        }

        settingView.fontSizeView.didHidePopUpSlider = { slider in

            let value = slider.value
            DZMReadConfigure.shared().fontSize = 18 + Int(value)
            weakSelf?.refreshReadView()
        }

        //        /// MARK: 字体
        settingView.fontView.fontBtn = { btn in

            DZMReadConfigure.shared().fontType = btn.tag
            weakSelf?.refreshReadView()
        }

        settingView.spacingView.changeSpacing = { sender in

            DZMReadConfigure.shared().paragraphStyleIndex = sender.tag
            weakSelf?.refreshReadView()
            XYLog(messsage:  sender.tag)
        }

        
        catalogueVC.clickZoom = {
            UIView.animate(withDuration: 0.25, animations: {
                weakSelf?.catalogueVC.view.frame = CGRect.init(x: -ScreenWidth, y: 0, width: ScreenWidth, height:ScreenHeight)
            })
        }

        bookModel.getchapterList { (chapterList, error) in
            if let list = chapterList {
                self.catalogueVC.chapters = list
                // 这里还有一个判断,就是数组有值,但是没有网络,且也没有缓存
                weakSelf?.bookModel.loadData(callBack: {
                    weakSelf?.loadSuccessCallback()
                })
            }else {
                // 如果数组为空 进一步判断有没网络
            }
        }

        /// 增加rightImtes
        let fullText = bookModel.currentChapter.fullText as NSString
        let body = fullText.substring(with: bookModel.currentChapter.pageRanges[pageIndex])
        rigthImtesVc = XYRigthItemController.init(bookIconImg:bookIcon.image!,bookName:bookName,body:body)
        rigthImtesVc.view.isHidden = true
        rigthImtesVc.delegate = self

        view.addSubview(rigthImtesVc.view)
        addChildViewController(rigthImtesVc)


    }

    func containsBody() {
        let fullText = bookModel.currentChapter.fullText as NSString
        let body = fullText.substring(with: bookModel.currentChapter.pageRanges[pageIndex])
        rigthImtesVc.iscontainsBody = XYBookMarkModel.containsBody(body: body)
    }


    func refreshReadView() {
        let newIndex = bookModel.index
        weak var weakSelf = self
        bookModel.updateIndex(newIndex, with: {
            let vc = XYReadDetailsController.init(index:self.pageIndex, frameRef: self.bookModel.currentChapter.pageFrameRefs[self.pageIndex], height: self.bookModel.currentChapter.pageHeights[self.pageIndex], model: self.bookModel.currentChapter,readModel:self.bookModel)
            self.pageVC.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
            weakSelf?.updateSliderValue()
        })
    }


    /// 进度条的跟新
    func updateSliderValue() {
        buttomView.slider.minimumValue = 1
        buttomView.slider.maximumValue = Float(bookModel.currentChapter.pageRanges.count)
        buttomView.slider.value = Float(CGFloat(pageIndex + 1))
    }


    func loadSuccessCallback() {
        /// 加载pageVC
        pageVC = UIPageViewController.init(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)

        //2. 添加pageViewControler
        addChildViewController(pageVC)
        view.backgroundColor = DZMReadConfigure.shared().readColor()
        view.insertSubview(pageVC.view, at: 0)
        pageVC.didMove(toParentViewController: self)
        //4. 设置pageViewController的数据源方法
        pageVC.dataSource = self
        pageVC.delegate = self
        let vc = XYReadDetailsController.init(index:pageIndex, frameRef: bookModel.currentChapter.pageFrameRefs[pageIndex], height: bookModel.currentChapter.pageHeights[pageIndex], model: bookModel.currentChapter,readModel:bookModel)
        pageVC.setViewControllers([vc], direction: .forward, animated: false, completion: nil)

        updateSliderValue()
    }

    func hiddenmenuView() {
         isHiddenTopBottonView = true
         dimissRightItmes()
        UIView.animate(withDuration: 0.25, animations: {
            self.buttomView.origin.y = ScreenHeight + 164
            self.topMenuView.origin.y = -64
            UIApplication.shared.isStatusBarHidden = true
        })
    }

    
    /// 点击展开,点击隐藏
    func clickAutoHiddenMenuView () {
          dimissRightItmes()
        self.buttomView.isHidden = false
        if isHiddenTopBottonView == false {
            isHiddenTopBottonView = true
            UIView.animate(withDuration: 0.25, animations: {
                self.buttomView.origin.y = ScreenHeight + 164
                self.topMenuView.origin.y = -64
                UIApplication.shared.isStatusBarHidden = true
            })
        }else {
            UIView.animate(withDuration: 0.25, animations: {
                self.topMenuView.origin.y = 0
                self.buttomView.origin.y = ScreenHeight - 164
                UIApplication.shared.isStatusBarHidden = false
            })
            self.isHiddenTopBottonView = false
        }
        self.settingView.isHidden = true
    }


    func gotoLastChapter() {
        weak var weakSelf = self
        if bookModel.chapters.count == 0 {
            //            HUDManager.xwj_showAnimatedSuccessHUD(label: "暂无更多数据")
            return
        }

        if bookModel.index == 0 {
            //            HUDManager.xwj_showAnimatedSuccessHUD(label: "暂无数据")
            return
        }else {
            let newIndex = bookModel.index - 1
            bookModel.updateIndex(newIndex, with: {
               weakSelf?.gotoChapterController()
            })
        }
        updateSliderValue()
    }

    /// 下一章
    func gotoNetChapter () {
        weak var weakSelf = self
        if bookModel.chapters.count == 0 {
            //            HUDManager.xwj_showAnimatedSuccessHUD(label: "暂无数据", time: 1.5)
            return
        }

        if bookModel.index != bookModel.chapters.count - 1 {
            let newIndex = bookModel.index + 1
            bookModel.updateIndex(newIndex, with: {
                weakSelf?.gotoChapterController()
                weakSelf?.updateSliderValue()
            })
        }else {
            //            HUDManager.xwj_showAnimatedSuccessHUD(label: "暂无更新")
            return
        }
    }

    // 跳下一个章节的时候,就不能去记录上一章节的页数了,因为你不能确定下一章的页数是否有这么多,比如,记录的页数是13 下一章万一没有就会数组越界
    func gotoChapterController() {
        let newIndex = bookModel.index
        weak var weakSelf = self
        bookModel.updateIndex(newIndex, with: {
            let vc = XYReadDetailsController.init(index:0, frameRef: self.bookModel.currentChapter.pageFrameRefs[0], height: self.bookModel.currentChapter.pageHeights[0], model: self.bookModel.currentChapter,readModel:self.bookModel)
            self.pageVC.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
            weakSelf?.updateSliderValue()
        })
    }
}


extension XYReaderController:XYBottomMenuViewDelegate {
    /// 上一章
    func bottmMenuBefore(bookListView:XYBottomMenuView) {
        dimissRightItmes()
        gotoLastChapter()
    }
    
    
    /// 下一章
    func bottmMenuAfter(bookListView:XYBottomMenuView) {

        dimissRightItmes()
        gotoNetChapter()
    }
    
    
    /// 目录
    func bottmMenuChapterList(bookListView:XYBottomMenuView) {

        catalogueVC.view.isHidden = false
        weak var weakSelf = self
        UIView.animate(withDuration: 0.25, animations: {
            weakSelf?.clickAutoHiddenMenuView()
        }) { (flag) in
            self.catalogueVC.view.frame = CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight)
        }
    }
    
    
    /// 夜间
    func bottmMenuNight(bookListView:XYBottomMenuView) {
        DZMReadConfigure.shared().colorIndex = 5
       refreshReadView()
        UIScreen.main.brightness = 0.5
    }
    
    /// 设置
    func bottmMenuSetting(bookListView:XYBottomMenuView) {
        self.settingView.isHidden = false
        self.buttomView.isHidden = true
    }
    
    /// 缓存
    func bottmMenuCache(bookListView:XYBottomMenuView) {
        // 要实现下载功能 必先实现缓存实现
        // 例:目录的缓存,章节的缓存,以及换源的缓存.
        // sql数据库是必然要使用的
        // 采用FMDB吧
        let vc = XYDownloadController.init(bookModel: bookModel)
        self.navigationController?.pushViewController(vc, animated: true)

    }
    
    /// 反馈
    func bottmMenuConmmitBug(bookListView:XYBottomMenuView){
        
    }
}


// MARK: - 换源
extension XYReaderController:XYTopMenuViewDelegate {
    
    func topmenuViewChangeSource(topMenuView:XYTopMenuView) {//切换源
        let vc = XWJChangeSoureVC.init(bookID: bookID)
        self.present(vc, animated: true, completion: nil)

    }
    
    
    /// 关闭
    ///
    /// - Parameter topMenuView: 关闭
    func topmenuViewClose(topMenuView:XYTopMenuView){ //关闭
        navigationController?.popViewController(animated: false)
    }


    /// 右边Itmes
    ///
    /// - Parameters:
    ///   - topMenuView: topMenuView
    ///   - rigthItems: rightItmes
    func topmenuViewRithItems(topMenuView:XYTopMenuView,rigthItems:UIButton) {
          containsBody()
        if isShowRithItmes == false {
//            let keyView = UIView()
           showRightItems()
        }else {
           dimissRightItmes()
        }
    }
}


// MARK: - 进度条的回调
extension XYReaderController:ASValueTrackingSliderDelegate {
    
    func sliderWillDisplayPopUpView(_ slider: ASValueTrackingSlider!) {
        
    }

    func sliderDidHidePopUpView(_ slider: ASValueTrackingSlider!) {

        var newIndex = Int(slider.value - 0.5)
        if newIndex > self.bookModel.currentChapter.pageRanges.count - 1 {
            newIndex = self.bookModel.currentChapter.pageRanges.count - 1
        }
        weak var weakSelf = self
        bookModel.updateIndex(bookModel.index) {
            let vc = XYReadDetailsController.init(index:newIndex, frameRef: self.bookModel.currentChapter.pageFrameRefs[newIndex], height: self.bookModel.currentChapter.pageHeights[newIndex], model: self.bookModel.currentChapter,readModel:self.bookModel)
            weakSelf?.pageVC.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
        }
    }
    
    
    func sliderWillHidePopUpView(_ slider: ASValueTrackingSlider!) {
        
    }
}


// MARK: - 因为刀哥的全屏侧滑,手势,会跟UIScorollView右滑动的时候,有冲突!故此方法
extension XYReaderController:UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {

        let bool = touch.view?.isInViewHirerackyOf(view:topMenuView)
        let bool1 = touch.view?.isInViewHirerackyOf(view:buttomView)
        let bool2 = touch.view?.isInViewHirerackyOf(view: catalogueVC.view)
        let bottomBool = touch.view?.isInViewHirerackyOf(view: settingView)
        let rigthImtesVcBool = touch.view?.isInViewHirerackyOf(view: rigthImtesVc.view)

        if bool == true || bool1 == true || bool2 == true || bottomBool == true || rigthImtesVcBool == true{
            return false
        }else {
            return true
        }
    }

    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return false
    }
}


extension XYReaderController: UIPageViewControllerDataSource {
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
         hiddenmenuView()
        var index = (viewController as! XYReadDetailsController).index
        if index > 0 {
            index -= 1
            if  index >  bookModel.currentChapter.pageFrameRefs.count - 1 {
                index = bookModel.currentChapter.pageFrameRefs.count - 1
            }
            let VC = XYReadDetailsController.init(index: index, frameRef: bookModel.currentChapter.pageFrameRefs[index], height: bookModel.currentChapter.pageHeights[index], model: bookModel.currentChapter,readModel:bookModel)

            return VC
        } else {
            if bookModel.index == 0 {
                //                HUDManager.xwj_showAnimatedSuccessHUD(label: "已经到尽头")
                return nil
            }else {
                index = bookModel.lastChapter.pageFrameRefs.count - 1
                let VC = XYReadDetailsController.init(index: index, frameRef: bookModel.lastChapter.pageFrameRefs[index], height: bookModel.lastChapter.pageHeights[index], model: bookModel.currentChapter,readModel:bookModel)
                bookModel.gotoLastChapter()
                return VC
            }

        }
    }

    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{
        hiddenmenuView()
        var index = (viewController as! XYReadDetailsController).index
        if index < bookModel.currentChapter.pageFrameRefs.count - 1 {
            index += 1

            let VC = XYReadDetailsController.init(index: index, frameRef: bookModel.currentChapter.pageFrameRefs[index], height: bookModel.currentChapter.pageHeights[index], model: bookModel.currentChapter,readModel:bookModel)

            return VC

        } else {
            index = 0
            let VC = XYReadDetailsController.init(index: index, frameRef: bookModel.nextChapter.pageFrameRefs[index], height: bookModel.nextChapter.pageHeights[index], model: bookModel.currentChapter,readModel:bookModel)
            bookModel.gotoNextChapter()
            return VC
        }
    }
}


extension XYReaderController: UIPageViewControllerDelegate {

    //// 翻页完成会进来这个回调
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        let previousIndex = (previousViewControllers[0] as! XYReadDetailsController).index
        let currentIndex = (pageViewController.viewControllers?[0] as! XYReadDetailsController).index

        if completed == true {
            updateSliderValue()
            //  如果碰到连续几章都只有1页, 那么下面的判断方式就有Bug, 暂时无解
            if previousIndex == 0 && currentIndex == bookModel.lastChapter.pageFrameRefs.count - 1 { //  翻到上一章
                if bookModel.index == 0 {
                    //                    HUDManager.xwj_showAnimatedSuccessHUD(label: "已经尽头")
                    return
                }else {
                    bookModel.gotoLastChapter()
                }
            }

            if previousIndex == bookModel.currentChapter.pageFrameRefs.count - 1 && currentIndex == 0 { // 翻到下一章
                if bookModel.index == bookModel.chapters.count - 1 {
                    //                    HUDManager.xwj_showAnimatedSuccessHUD(label: "暂无更新")
                    return
                }else {
                    bookModel.gotoNextChapter()
                    XYLog(messsage: "翻页了")
                }
            }
        }
    }
}

extension XYReaderController {
    func showRightItems() {
        isShowRithItmes = true
       rigthImtesVc.view.isHidden = false
    }
    func dimissRightItmes() {
        weak var weakSelf = self
        UIView.animate(withDuration: 0.25) {
            weakSelf?.isShowRithItmes = false
           weakSelf?.rigthImtesVc.view.isHidden = true
        }
    }
}


extension XYReaderController:XYRigthItemControllerDelegate {
    func rightImtesGotoBookDetails() {
         XYLog(messsage: "跳转书籍详情")
    }

    func rightItmeResoure() {
        XYLog(messsage: "换源")
    }


    /// 书签添加取消时间 2018/01/06 xwj
    func rightItmeaddBookMake() {

        XYBookMarkModel.createTable()
        let fullText = bookModel.currentChapter.fullText as NSString
        let body = fullText.substring(with: bookModel.currentChapter.pageRanges[pageIndex])

        let contain = XYBookMarkModel.containsBody(body: body)
        if contain == true {
            // 证明有 删除
            XYBookMarkModel.remove(body: body, success: { [weak self](true) in
                self?.dimissRightItmes()
                delay(0.25, task: {
                      MBProgressHUD.wj_showSuccess("取消书签成功")
                })

            }, failure: { (error) in
                delay(0.25, task: {
                      MBProgressHUD.wj_showError(String.init(format: "取消书签失败%@", error.localizedDescription))
                })
            })

        }else {

            let time = getCurrentStringTime()
            let book = XYBookMark.init(body: body, title: bookModel.currentChapter.titleString, time: time, chapterIndex: bookModel.index)

            XYBookMarkModel.insertBookChater(book: book , success: {[weak self] (true) in
                self?.dimissRightItmes()
                  self?.containsBody()
                delay(0.25, task: {
                     MBProgressHUD.wj_showSuccess("添加书签成功")
                })

            }, failure: { (error) in
                delay(0.25, task: {
                     MBProgressHUD.wj_showError(String.init(format: "添加书签失败%@", error.localizedDescription))
                })
            })
        }
    }


    func rightImteShare() {
        XYLog(messsage: "分享")
    }

    func rightImteDownload() {
        /// 跳进的是缓存页面
        let vc = XYDownloadController.init(bookModel: bookModel)
        self.navigationController?.pushViewController(vc, animated: true)
    }

}
